/*
 * Created on Sep 28, 2006
 */
package com.scalar.chiptrack.operations.distributor.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.distributor.DistLineItem;
import com.scalar.chiptrack.operations.distributor.dao.DistributorDao;
import com.scalar.chiptrack.operations.distributor.forms.DistributorSalesForm;
import com.scalar.chiptrack.operations.packingslip.actions.SearchPackingSlipAction;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.CustomerRelationshipDAO;
import com.scalar.chiptrack.sales.dao.NewCustomerDAO;
import com.scalar.chiptrack.sales.CustomerRelationship;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.Functionality;

/**
 * @author ravi
 */
public class DistributorSalesAction extends ChipTrackAction
{
    public ActionForward execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        HttpSession session = request.getSession();
        User user 			= (User) session.getAttribute ( SessionKeys.USER_KEY );
        HashMap<String,String> errors 		= new HashMap<String,String>();
        HashMap<String,String> info 		= new HashMap<String,String>();
        String forward 		= "success";
        String action 		= request.getParameter( "action" );

        DBTransaction dbTransaction     = null;
        boolean success                 = false;

        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, "/distributorSalesSearch.do?" + request.getQueryString() );
            return ( mapping.findForward( "login" ) );
        }
        else
        {
            if ( user.isActionAllowed ( Functionality.DISTRIBUTOR_SALES_ORDER , User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }
        }

        if( request.getAttribute( SessionKeys.INFO_MESSAGES ) != null )
        {
            info.putAll( ( HashMap ) request.getAttribute( SessionKeys.INFO_MESSAGES ) );
        }

        if( request.getAttribute( SessionKeys.ERROR_MESSAGES ) != null )
        {
            errors.putAll( ( HashMap ) request.getAttribute( SessionKeys.ERROR_MESSAGES ) );
        }

        DistributorSalesForm salesForm = (DistributorSalesForm) form;
        if ( action == null ){ 	action = ""; }

        if( "create".equalsIgnoreCase( action ) )
        {
            resetDistSalesOrderForm( salesForm );
            session.removeAttribute( "lineItemWithPulledLotDetails" );

            ArrayList<DistLineItem> lineItemList = new ArrayList<DistLineItem>();
            lineItemList.add( new DistLineItem() );
            lineItemList.add( new DistLineItem() );
            salesForm.setLineItemList( lineItemList );

            Calendar cal   	= Calendar.getInstance();
            salesForm.setSalesOrderDate(  StringUtils.formatDateToString( cal.getTime() ) );
            salesForm.setSalesOrderNo( DistributorDao.genarateAutomatedDistSalesOrderNumber(1));
            
            forward = "success";
        }
        else if( "addmore".equalsIgnoreCase( action ) )
        {
            salesForm.getLineItemList().add( new DistLineItem() );

            forward = "success";
        }
        else if( "save".equalsIgnoreCase( action ) )
        {
            forward = "dist_sales_orders_search";

            try
            {
                HashMap lineItemWisePulledLotsMap = ( HashMap ) session.getAttribute("lineItemWithPulledLotDetails");

                /*if( lineItemWisePulledLotsMap != null && lineItemWisePulledLotsMap.isEmpty() == false )
                {
                    Iterator it = lineItemWisePulledLotsMap.keySet().iterator();
                    ArrayList al = null;
                    String lineItemNo = null;
                    DistributorInventory inventory = null;
                    while( it.hasNext() )
                    {
                        lineItemNo = ( String )  it.next();
                        al = ( ArrayList ) lineItemWisePulledLotsMap.get( lineItemNo );
                        if( al != null && al.size() > 0 )
                        {
                            for( int i = 0; i < al.size(); i++ )
                            {
                                inventory = ( DistributorInventory ) al.get(i);
                                System.out.println( lineItemNo + " ######## - SalesAction - LotNo = " + inventory.getLot_number() + " Pulled_Qty = " + inventory.getQty_pulled() );
                            }
                        }
                    }
                }*/

                dbTransaction = DBTransaction.getInstance();
                dbTransaction.begin();

                DistributorDao.saveDistSalesOrderDetails( dbTransaction, salesForm, user);
                DistributorDao.saveDistSOLineItemDetails( dbTransaction, salesForm );
                DistributorDao.saveDistSOLineItemInventoryDetails( dbTransaction, salesForm, lineItemWisePulledLotsMap );

                success = true;
            }
            catch( Exception e )
            {
                forward = "dist_sales_orders_search";
                errors.put ( "Could not save Distributor Sales Order Information", null );
                e.printStackTrace();
            }
            finally
            {
                if( dbTransaction != null ){
                    if( success == true ){
                        try{
                            dbTransaction.commit();
                            info.put ( "Distributor Sales Order Information Saved Successfully ", null );
                        }catch( Exception e ){
                            e.printStackTrace();
                            errors.put ( "Error while committing the database ", null );
                        }
                    }
                    else
                    {
                        try{
                            dbTransaction.rollback();
                        }catch( Exception e ){
                            e.printStackTrace();
                            errors.put ( "Error occurred while rolling back", null );
                        }
                    }
                }

                /*request.setAttribute( "searchCustomerList", NewCustomerDAO.getAllCustomerNamesByCustomerTypeId( 2 ) );
                request.setAttribute( "distributorList", NewCustomerDAO.getAllDistributorNamesByUserType( null, user, true ) );
                request.setAttribute( "productList", SearchPackingSlipAction.loadManufacturingProducts () );
                request.setAttribute( "yearList", getYearList() );*/
                resetDistSalesOrderForm( salesForm );
                salesForm.setDistributorId("0");
                session.removeAttribute( "lineItemWithPulledLotDetails" );
            }
        }
        else if( "view".equalsIgnoreCase( action ) )
        {

            String distributorSalesOrder = request.getParameter("distributorSalesOrder");
            
            forward = "view";
            int distSalesOrderId = -1;
            try
            {
                try
                {
                    distSalesOrderId = Integer.parseInt( request.getParameter("distSalesOrderId") );
                }catch( NumberFormatException nfe ) {};

                DistributorDao.loadCompleteBumpReleaseDetails( salesForm, distSalesOrderId );

                if("cancel".equalsIgnoreCase(distributorSalesOrder.trim()))
                {
                     salesForm.setDistributorSalesOrder(1);
                }
                else if("close".equalsIgnoreCase(distributorSalesOrder.trim()))
                {
                    salesForm.setDistributorSalesOrder(2);
                }
                else
                {
                    salesForm.setDistributorSalesOrder(0);                    
                }

                ArrayList endCustomerListLVB   = new ArrayList();
                ArrayList endCustomerList   = CustomerRelationshipDAO.getODMRelationshipInformation( salesForm.getDistributorId() );
                CustomerRelationship cr     = null;

                for( int i = 0; i < endCustomerList.size(); i++ )
                {
                    cr = ( CustomerRelationship ) endCustomerList.get( i );
                    endCustomerListLVB.add ( new LabelValueBean ( cr.getChildCustomerName(), cr.getChildCustomerId() + "" ) );
                }
                request.setAttribute( "endCustomerList", endCustomerListLVB );
            }
            catch( Exception e )
            {
                forward = "dist_sales_orders_search";
                errors.put ( "Could not retrive the Distributor Sales Order Information", null );
                e.printStackTrace();
            }
        }
        else if( "modify".equalsIgnoreCase( action ) )
        {
            forward = "edit";
            int distSalesOrderId = -1;
            try
            {
                try
                {
                    distSalesOrderId = Integer.parseInt( request.getParameter("distSalesOrderId") );
                }
                catch( NumberFormatException nfe ) {};

                DistributorDao.loadCompleteBumpReleaseDetails( salesForm, distSalesOrderId );
                ArrayList endCustomerListLVB   = new ArrayList();
                ArrayList endCustomerList   = CustomerRelationshipDAO.getODMRelationshipInformation( salesForm.getDistributorId() );
                CustomerRelationship cr     = null;
                for( int i = 0; i < endCustomerList.size(); i++ )
                {
                     cr = ( CustomerRelationship ) endCustomerList.get( i );
                     endCustomerListLVB.add ( new LabelValueBean ( cr.getChildCustomerName(), cr.getChildCustomerId() + "" ) );
                }
                request.setAttribute( "endCustomerList", endCustomerListLVB );
                //request.setAttribute( "customerList", CustomerDAO.getAllCustomerNamesNoStringsAttached() );
            }
            catch( Exception e )
            {
                forward = "dist_sales_orders_search";
                errors.put ( "Could not retrive the Distributor Sales Order Information", null );
                e.printStackTrace();
            }
        }
        else if( "cancel".equalsIgnoreCase( action ) )
         {
             forward = "dist_sales_orders_search";

             try
             {
                 dbTransaction = DBTransaction.getInstance();
                 dbTransaction.begin();

                 salesForm.setStatus("cancel");

                 DistributorDao.saveDistSalesOrderDetails( dbTransaction, salesForm, user);
                 //DistributorDao.saveDistSOLineItemDetails( dbTransaction, salesForm );
                 DistributorDao.cancelDistributorInventory( dbTransaction, salesForm );

                 success = true;
             }
             catch( Exception e )
             {
                 forward = "dist_sales_orders_search";
                 errors.put ( "Could not save Distributor Sales Order Information", null );
                 e.printStackTrace();
             }
             finally
             {
                 if( dbTransaction != null )
                 {
                     if( success == true )
                     {
                         try
                         {
                             dbTransaction.commit();
                             info.put ( "Distributor Sales Order Information Saved Successfully ", null );
                         }
                         catch( Exception e )
                         {
                             e.printStackTrace();
                             errors.put ( "Error while committing the database ", null );
                         }
                     }
                     else
                     {
                         try
                         {
                             dbTransaction.rollback();
                         }
                         catch( Exception e )
                         {
                             e.printStackTrace();
                             errors.put ( "Error occurred while rolling back", null );
                         }
                     }
                 }
                 resetDistSalesOrderForm( salesForm );
                 salesForm.setDistributorId("0");
                 session.removeAttribute( "lineItemWithPulledLotDetails" );
             }
         }
         else if( "close".equalsIgnoreCase( action ) )
         {
             forward = "dist_sales_orders_search";

             try
             {
                 dbTransaction = DBTransaction.getInstance();
                 dbTransaction.begin();

                 salesForm.setStatus("close");
                 DistributorDao.saveDistSalesOrderDetails( dbTransaction, salesForm, user);
                 //DistributorDao.saveDistSOLineItemDetails( dbTransaction, salesForm );
                 //DistributorDao.saveDistSOLineItemInventoryDetails( dbTransaction, salesForm, lineItemWisePulledLotsMap );

                 success = true;
             }
             catch( Exception e )
             {
                 forward = "dist_sales_orders_search";
                 errors.put ( "Could not save Distributor Sales Order Information", null );
                 e.printStackTrace();
             }
             finally
             {
                 if( dbTransaction != null )
                 {
                     if( success == true )
                     {
                         try
                         {
                             dbTransaction.commit();
                             info.put ( "Distributor Sales Order Information Saved Successfully ", null );
                         }
                         catch( Exception e )
                         {
                             e.printStackTrace();
                             errors.put ( "Error while committing the database ", null );
                         }
                     }
                     else
                     {
                         try
                         {
                             dbTransaction.rollback();
                         }
                         catch( Exception e )
                         {
                             e.printStackTrace();
                             errors.put ( "Error occurred while rolling back", null );
                         }
                     }
                 }
                 resetDistSalesOrderForm( salesForm );
                 salesForm.setDistributorId("0");
                 session.removeAttribute( "lineItemWithPulledLotDetails" );
             }
         }
        if( "create".equalsIgnoreCase( action ) || "loadEndCustomers".equalsIgnoreCase( action ) || "addmore".equalsIgnoreCase( action ) )
        {
            ArrayList endCustomerListLVB   = new ArrayList();
            ArrayList endCustomerList   = CustomerRelationshipDAO.getODMRelationshipInformation( salesForm.getDistributorId() );
            CustomerRelationship cr     = null;
            if ("create".equalsIgnoreCase( action ) || "loadEndCustomers".equalsIgnoreCase( action ))
            {
                salesForm.setNewEndCustomerName("");
                salesForm.setCustomer_Id("0");
            }

            for( int i = 0; i < endCustomerList.size(); i++ )
            {
                 cr = ( CustomerRelationship ) endCustomerList.get( i );
                 endCustomerListLVB.add ( new LabelValueBean ( cr.getChildCustomerName(), cr.getChildCustomerId() + "" ) );
            }
            request.setAttribute( "endCustomerList", endCustomerListLVB );
        }

        request.setAttribute( SessionKeys.INFO_MESSAGES, info );
        request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );

        request.setAttribute( "searchCustomerList", NewCustomerDAO.getAllCustomerNamesByCustomerTypeId(2) );
        request.setAttribute( "distributorList", NewCustomerDAO.getAllDistributorNamesByUserType( null, user, false ) );
        request.setAttribute( "productList", SearchPackingSlipAction.loadManufacturingProducts () );
        request.setAttribute( "yearList", getYearList() );
        
        return( mapping.findForward( forward ) );
    }
    private void resetDistSalesOrderForm( DistributorSalesForm salesForm )
    {
        salesForm.setDistSalesOrderId( -1 );
        salesForm.setSalesOrderNo( "" );
        salesForm.setCustomerPO( "" );
        salesForm.setCustomer_Id( "" );
        salesForm.setDistributorId( "" );
        salesForm.setShipDate( "" );
        salesForm.setSalesOrderDate( "" );

        salesForm.setLineItemList( null );
    }

    private ArrayList getYearList()
    {
		int year = 2000;
		ArrayList yearList = new ArrayList();
		for ( int i = 0; i <= 15; i++ )
		{
			yearList.add( new LabelValueBean( year+"", year+"" ) );
			year++;
		}
        return yearList;
    }
}
